package com.h2cloud.JUCTest.reentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import static com.h2cloud.JUCTest.TimeUtil.Sleeper.sleep;


@Slf4j(topic = "c.TestCondition")
public class TestCondition {
	static ReentrantLock lock = new ReentrantLock();
	static Condition waitCigaretteQueue = lock.newCondition();
	static Condition waitbreakfastQueue = lock.newCondition();
	static volatile boolean hasCigrette = false;
	static volatile boolean hasBreakfast = false;

	public static void main(String[] args) throws InterruptedException {
		Thread ttt = new Thread(() -> {
			try {
				lock.lock();
				while (!hasCigrette) {
					waitCigaretteQueue.await();
				}
				if (!Thread.currentThread().isInterrupted()) {
					log.debug("等到了它的烟");
				} else {
					log.debug("Interrupt 在唤醒之后被中断");
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.debug("Interrupt 在唤醒之前被中断");
			} finally {
				lock.unlock();
			}
		}, "ttt");
		ttt.start();
		// 等待一秒，让上面的 ttt线程进入条件队列，再往下执行
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// ttt.interrupt();

		lock.lock();
		// 增加等待队列中的线程数量
		// for (int i = 0; i < 2; i++) {
		// 	int value = i;
		// 	new Thread(() -> {
		// 		lock.lock();
		// 		log.info("thread_" + value);
		// 		lock.unlock();
		// 	}, "t" + value).start();
		// }
		// // 让 100个线程全部加入等待队列，再往下执行
		// try {
		// 	Thread.sleep(2000);
		// } catch (InterruptedException e) {
		// 	e.printStackTrace();
		// }

		// 唤醒 ttt线程，加入等待队列的尾部
		// log.debug("送烟来了");
		// hasCigrette = true;

		// try {
		// 	Thread.sleep(2000);
		// } catch (InterruptedException e) {
		// 	e.printStackTrace();
		// }
		ttt.interrupt();
		Thread.sleep(2000);
		waitCigaretteQueue.signal();

		lock.unlock();

	}
}
